package com.xlcszsgc.module.resource.ui.controller;


import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.xlcszsgc.core.configure.PropertiesVo;
import com.xlcszsgc.core.page.PageInfoBean;
import com.xlcszsgc.core.servicetemplate.treetemplate.jsonbean.JsonTreeBean;
import com.xlcszsgc.core.util.PropertyUtil;
import com.xlcszsgc.module.Constants;
import com.xlcszsgc.module.blob.service.IBlobService;
import com.xlcszsgc.module.blob.ui.commond.BaseBlobCommond;
import com.xlcszsgc.module.blob.ui.controller.BaseBlobController;
import com.xlcszsgc.module.clob.domain.BaseClob;
import com.xlcszsgc.module.clob.service.IClobService;
import com.xlcszsgc.module.clob.ui.commond.BaseClobCommond;
import com.xlcszsgc.module.resource.vo.CategoryVo;


/**
 * @Title: ResourceController.java
 * @Package com.xlcszsgc.module.resource.ui.controller
 * @Description: 首页文章、图片展现，后台文章、图片维护统一入口</p>
 * 文章详细查看{@link com.xlcszsgc.module.clob.ui.controller.BaseClobController#view(org.springframework.ui.Model, 
 * javax.servlet.http.HttpServletRequest, com.xlcszsgc.module.clob.ui.commond.BaseClobCommond)}}}
 * </p>
 * 图片查看{@link com.xlcszsgc.module.blob.ui.controller.BaseBlobController#showImage(
 * javax.servlet.http.HttpServletResponse, com.xlcszsgc.module.blob.ui.commond.BaseBlobCommond)}
 * @author Zhaoqt  
 * @date 2014-5-26 上午1:41:06
 * @version V1.0
 */
@Controller(value = "com.xlcszsgc.module.resource.ui.controller.ResourceController")
@RequestMapping(value = {ResourceController.modulePath, ResourceController.portalPath,ResourceController.anliPath,ResourceController.wordPath})
public class ResourceController {

	public static final String anliPath = "/module/anli";
	
	public static final String modulePath = "/module/resource";
	
	public static final String portalPath = "/portal/resource";
	
	public static final String wordPath = "/module/word";
	
	@Resource(name = "com.xlcszsgc.module.clob.service.impl.ClobServiceImpl")
	private IClobService clobService;
	@Resource(name = "com.xlcszsgc.module.blob.service.impl.BlobServiceImpl")
	private IBlobService blobService;
	@Resource(name = "com.xlcszsgc.module.resource.vo.CategoryVo")
	private CategoryVo categoryVo;
	
	@Autowired
	@Qualifier(value = "propertiesVo")
	private PropertiesVo propertiesVo; 
	
	/**
	 * 文章列表
	 * @Title: listDocument
	 * @param model
	 * @param request
	 * @param baseClobCommond
	 * @return
	 */
	@RequestMapping("/documentList")
	public String documentList(Model model, 
			HttpServletRequest request, BaseClobCommond baseClobCommond) throws Exception {
		baseClobCommond.setPaging(true); //文章列表必须开启分页查询
		if(PropertyUtil.objectNotEmpty(baseClobCommond.getSearchCategoryCode())) {
			clobService.listClob(baseClobCommond);
		}
		model.addAttribute("listDocument", baseClobCommond);
		return ResourceController.wordPath + "/documentList.jsp";
	}
	
	/**
	 * 发布/去掉发布
	 * @Title: updateDocumentPublish
	 * @param model
	 * @param request
	 * @param baseClobCommond
	 * @return
	 */
	@RequestMapping("/updateDocumentPublish")
	public String updateDocumentPublish(Model model, 
			HttpServletRequest request, BaseClobCommond baseClobCommond) throws Exception  {
		BaseClob baseClob = new BaseClob();
		if(baseClobCommond.getPublish() != null) {
			if(baseClobCommond.getPublish().indexOf("IS_PUBLISH") != -1) {
				baseClob.setPublish(Constants.IS_PUBLISH);
			} else if(baseClobCommond.getPublish().indexOf("NO_PUBLISH") != -1) {
				baseClob.setPublish(Constants.NO_PUBLISH);
			}
			baseClobCommond.setBaseClob(baseClob);
			clobService.batchDynamicUpdateClob(baseClobCommond);
		}
		return  ResourceController.wordPath + "/documentList.do";
	}
	
	/**
	 * 文章排序
	 * @Title: sortDocument
	 * @param model
	 * @param request
	 * @param baseClobCommond
	 * @return
	 */
	@RequestMapping("/sortDocument")
	public String sortDocument(Model model, 
			HttpServletRequest request, BaseClobCommond baseClobCommond)  throws Exception {
		String searchClobIds[] = {baseClobCommond.getBaseClob().getClobId()};
		baseClobCommond.setSearchClobIds(searchClobIds);
		clobService.batchDynamicUpdateClob(baseClobCommond);
		return  ResourceController.wordPath + "/documentList.do";
	}
	/**
	 * 文章分类tree
	 * @Title: findDocumentTree
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/findDocumentTree")
	public @ResponseBody
	List<JsonTreeBean> findDocumentTree(Model model, HttpServletRequest request)
			throws Exception {
		List<JsonTreeBean> treeBeanList=new ArrayList<JsonTreeBean>();
		String id=request.getParameter("fid");
		if(id==null||"".equals(id)){
			JsonTreeBean jt=this.buildJsonTreeBean("1","-2","文章分类","closed");
			treeBeanList.add(jt);
		}else{
			JsonTreeBean jt1=this.buildJsonTreeBean("news","1","新闻中心","open");
			JsonTreeBean jt2=this.buildJsonTreeBean("zxcs","1","装修尝试","open");
			treeBeanList.add(jt1);
			treeBeanList.add(jt2);
		}
		return treeBeanList;
	}
	
	private JsonTreeBean buildJsonTreeBean(String id,String parentId,String text,String state){
		JsonTreeBean bean =new JsonTreeBean();
		bean.setId(id);
		bean.setState(state);
		bean.setParentID(parentId);
		bean.setText(text);
		return bean;
	}
	/**
	 * 文章首页展现列表
	 * @Title: showDocumentList
	 * @param model
	 * @param request
	 * @param baseClobCommond
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/viewDocumentList")
	public String viewDocumentList(Model model, 
			HttpServletRequest request, BaseClobCommond baseClobCommond) throws Exception { 
		baseClobCommond.setPaging(true); //文章列表必须开启分页查询
		baseClobCommond.setRowCount(18);
		baseClobCommond.setSearchPublish(Constants.IS_PUBLISH);
		if(PropertyUtil.objectNotEmpty(baseClobCommond.getSearchCategoryCode())) {
			clobService.listClob(baseClobCommond);
		}
		baseClobCommond.setCategoryVo(categoryVo);
		model.addAttribute("baseClobCommond", baseClobCommond);
		return ResourceController.portalPath + "/viewDocumentList.jsp";
	}
	

	/**
	 * 首页案例图片展现
	 * @Title: viewCaseView
	 * @param model
	 * @param request
	 * @param baseBlobCommond
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/indexSmallPictureView")
	public String indexSmallPictureView(Model model, 
			HttpServletRequest request, BaseBlobCommond baseBlobCommond) throws Exception {
		baseBlobCommond.setPaging(true);
		baseBlobCommond.setSearchBigBlob(false);
		PageInfoBean pageInfoBean = baseBlobCommond.getPageBean();
		pageInfoBean.setRowCount(7); // 每页显示7条数据
		if(PropertyUtil.objectNotEmpty(baseBlobCommond.getSearchCategoryCode())) {
			blobService.listBlob(baseBlobCommond);
		}
		baseBlobCommond.setViewUrl(request.getContextPath() + BaseBlobController.portalPath + "/showImage.do?searchBlobId=");
		model.addAttribute("indexPictureView", baseBlobCommond);
		return ResourceController.portalPath + "/indexPictureView.jsp";
	}
	
	/**
	 * 异步查询大图信息进行首页图片浏览器<a>信息装载
	 * @Title: indexBigPictureView
	 * @param model
	 * @param request
	 * @param baseBlobCommond
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/indexBigPictureView")
	@ResponseBody
	public String indexBigPictureView(Model model, 
			HttpServletRequest request, BaseBlobCommond baseBlobCommond) throws Exception {
		JSONArray jsonArray = new JSONArray();
		baseBlobCommond.setPaging(false);
		baseBlobCommond.setSearchBigBlob(false);
		if(PropertyUtil.objectNotEmpty(baseBlobCommond.getSearchCategoryCode())) {
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
			jsonArray  = JSONArray.fromObject(blobService.listBlob(baseBlobCommond), jsonConfig);
		}
		return jsonArray.toString();
	}
	
	/**
	 * 添加文章
	 * @Title: addDocument
	 * @param model
	 * @param request
	 * @param baseClobCommond
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/addDocument")
	public String addDocument(Model model, 
			HttpServletRequest request, BaseClobCommond baseClobCommond) throws Exception {
		clobService.addClob(baseClobCommond.getBaseClob());
		model.addAttribute("baseClobCommond", baseClobCommond);
		return ResourceController.wordPath + "/addWord.jsp";
	}
	
	/**
	 * 删除文章(支持批量)
	 * @Title: deleteDocument
	 * @param model
	 * @param request
	 * @param baseClobCommond
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/deleteDocument")
	public String deleteDocument(Model model, 
			HttpServletRequest request, BaseClobCommond baseClobCommond) throws Exception {
		clobService.batchdeleteClobById(baseClobCommond);
		return  ResourceController.wordPath + "/documentList.do";
	}
	
	/**
	 * 修改文章
	 * @Title: updateDocument
	 * @param model
	 * @param request
	 * @param baseClobCommond
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updateDocument")
	public String updateDocument(Model model, 
			HttpServletRequest request, BaseClobCommond baseClobCommond) throws Exception {
		clobService.updateClob(baseClobCommond.getBaseClob());
		return  ResourceController.wordPath + "/documentList.do";
	}
	
	/**
	 * 预修改文章
	 * @Title: preUpdateDocument
	 * @param model
	 * @param request
	 * @param baseClobCommond
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/preUpdateDocument")
	public String preUpdateDocument(Model model, 
			HttpServletRequest request, BaseClobCommond baseClobCommond) throws Exception {
		model.addAttribute("document", clobService.getBaseClob(baseClobCommond));
		return ResourceController.wordPath + "/updateDocument.jsp";
	}
	
	/**
	 * 包含大图小图
	 * @Title: addPicture
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/addPicture")
	public String addPicture(Model model, HttpServletRequest request,
			BaseBlobCommond baseBlobCommond) throws Exception {
		 String error="";
		if(baseBlobCommond.getSmallFile().getSize()>0&&
				baseBlobCommond.getBigFile().getSize()>0) {
			Long imgMaxSize = new Long(Integer.valueOf(propertiesVo.getUploadImgSize()) * 1024 * 1024);
			Long bigImgMaxSize = new Long(Integer.valueOf(propertiesVo.getUploadBigImgSize()) * 1024 * 1024);
			String imgFormat = propertiesVo.getUploadImgFormat();
//			MultipartFile file = baseBlobCommond.getFile();
//			MultipartFile bigFile = baseBlobCommond.getBigfile();
//			if(file.getSize() > imgMaxSize) {
//				throw new Exception("上传小图大小超出限制！");
//			}
//			if(bigFile.getSize() > bigImgMaxSize) {
//				throw new Exception("上传大图的大小超出限制！");
//			}
			CommonsMultipartFile file = baseBlobCommond.getSmallFile();
			CommonsMultipartFile bigFile = baseBlobCommond.getBigFile();
			boolean flag=true;
			if(file.getSize() > imgMaxSize) {
				error="小图过大,最大为1m";
				flag=false;
			}
			if(bigFile.getSize() > bigImgMaxSize) {
				error+="大图过大,最大为"+propertiesVo.getUploadBigImgSize()+"m";
				flag=false;
			}
			String fileName = file.getOriginalFilename();
			String extensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
			String bigFileName = bigFile.getOriginalFilename();
			String bigExtensionName = bigFileName.substring(bigFileName.lastIndexOf(".") + 1);
			if(imgFormat.toLowerCase().indexOf(extensionName.toLowerCase()) < 0) {
				error+="小图的图片类型不在"+imgFormat+"中";
				flag=false;
			}
			if(imgFormat.toLowerCase().indexOf(bigExtensionName.toLowerCase()) < 0) {
				error+="大图的类型不在"+imgFormat+"中";
				flag=false;
			}
			if(flag){
				blobService.addBigBlob(baseBlobCommond);
				error="上传成功";
			}
			
		}else{
			error="未找到待上传的图片";
		}
		baseBlobCommond.setErrorMsg(error);
		request.setAttribute("baseCommond", baseBlobCommond);
		return ResourceController.anliPath+"/uploadImg.jsp";
	}
	
	/**
	 * 批量上传
	 * @Title: batchAddPicture
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/batchAddPicture")
	public void batchAddPicture(HttpServletRequest request, HttpServletResponse response, BaseBlobCommond baseBlobCommond) throws Exception {
		blobService.batchAddBlob(baseBlobCommond, request, response);
	}
	
	/**
	 * 删除图片(支持批量)
	 * @Title: deletePicture
	 * @param model
	 * @param request
	 * @param baseClobCommond
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/deletePicture")
	@ResponseBody
	public String deletePicture(Model model, 
			HttpServletRequest request, BaseBlobCommond baseBlobCommond) throws Exception {
		blobService.batchdeleteClobById(baseBlobCommond);
		return "{ok}";
	}
}
